import React, {PureComponent} from 'react'
import PropTypes from 'prop-types'
import {Text} from 'react-native'
import moment from "moment";
import 'moment/locale/zh-cn'

moment.locale('zh-cn')

class TimeAgo extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      timer: null
    }
  }

  componentDidMount() {
    this.createTimer();
  }

  createTimer = () => {
    this.setState({
      timer: setTimeout(() => {
        this.update();
      }, this.props.interval)
    });
  };

  componentWillUnmount() {
    clearTimeout(this.state.timer);
  }

  update = () => {
    this.forceUpdate();
    this.createTimer();
  };

  render() {
    const {time, hideAgo,...rest} = this.props;
    return (
      <Text {...rest}>
        {moment(time).fromNow(hideAgo)}
      </Text>
    )
  }
}

TimeAgo.propTypes = {
  time: PropTypes.any,
  hideAgo: PropTypes.bool,
  interval: PropTypes.number,
}

TimeAgo.defaultProps = {
  hideAgo: false,
  interval: 60000
}

export default TimeAgo
